//
//  ViewController.m
//  course1
//
//  Created by yc on 15/6/27.
//  Copyright (c) 2015年 yc. All rights reserved.
//

#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "Person.h"
#import "Header.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self.login addTarget:self action:@selector(doLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    NSDictionary *dict = @{ @"userid":@"10051328", @"password":@"518886yc", @"device":@"ios" };
    NSString *requestAddress = @"http://test.beta.jilvinfo.com/get_information.php";

    
    HttpManager *car = [[HttpManager alloc]init];
    [car sendGetOfUrl:(requestAddress) andMap:(dict) onSuccess:^(NSString *result) {
        
        NSLog(@"result = %@", result);
    } failure:^(NSError *error) {
        
        NSLog(@"failed error = %@", error);
    }];
    
    
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    
//    // 带参数的GET请求
//    [manager POST:requestAddress
//      parameters:dict
//         success:^(AFHTTPRequestOperation *operation, id responseObject) {
//             
//             NSString *requestTmp = [NSString stringWithString:operation.responseString];
//          //   NSLog(@"result1 = %@", requestTmp);
//             
//             NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
//             
//             NSError *error = nil;
//             NSDictionary * rootDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:&error];
//             NSDictionary *result = [rootDic objectForKey:@"result"];
//             NSString *code = [result objectForKey:@"code"];
//             NSLog(@"code = %@", code);
//             
//         
//         }
//         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//             NSLog(@"%@", error);
//         }];
    
    // 从应用程序包中加载模型文件
    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    // 传入模型对象，初始化NSPersistentStoreCoordinator
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    // 构建SQLite数据库文件的路径
    NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSURL *url = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"person.data"]];
    // 添加持久化存储库，这里使用SQLite作为存储库
    NSError *error = nil;
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    if (store == nil) { // 直接抛异常
        [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
    }
    // 初始化上下文，设置persistentStoreCoordinator属性
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.persistentStoreCoordinator = psc;
    // 用完之后，记得要[context release];
    
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
    person.name = @"MJ";
    person.age = [NSNumber numberWithInt:27];
    
    BOOL success = [context save:&error];
    if (!success) {
        [NSException raise:@"访问数据库错误" format:@"%@", [error localizedDescription]];
    }
    
    // 初始化一个查询请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    // 设置要查询的实体
    request.entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"Itcast-1"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*Itcast-1*)
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*Itcast-1*"];
//    request.predicate = predicate;
    NSArray *objs = [context executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    // 遍历数据
    NSLog(@"start print person info");
    for (NSManagedObject *obj in objs) {
        NSLog(@"name=%@, age = %@", [obj valueForKey:@"name"], [obj valueForKey:@"age"]);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)doLogin:(id)sender {
    
    NSString *userIdText = self.userId.text;
    NSString *pwText = self.pw.text;
    NSString *msg = @"登录失败";
//    
//    msg = [@"userId: " stringByAppendingString:[userIdText stringByAppendingString:[@" password: " stringByAppendingString:pwText]]];
    
    if(![userIdText isEqualToString:@"admin"]){
        
        msg = @"用户id错误";
    }else if(![pwText isEqualToString:@"admin"]){
        msg = @"用户密码错误";
    }else{
        [self performSegueWithIdentifier:@"second" sender:self];
        return;
    }
    
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    
    [myAlertView show];
}
@end
